#pragma once
#include <iostream>
#include <string>
#include <filesystem> //C++17支持 用来创建路径
#include <fstream>
#include <sstream> //流式的格式化控制
#include <memory>
#include <unistd.h>
#include <time.h>
#include <cstdio>
#include "Mutex.hpp"

namespace LogModule
{
    using namespace MutexModule;
    const std::string gsep = "\r\n"; // 分隔符
    // 刷新策略基类:1.显示器打印 2.向制定文件写入
    class LogStrategy
    {
    public:
        ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 显示器刷新的派生类
    class ConsoleStrategy : public LogStrategy
    {
    public:
        ConsoleStrategy() {}
        ~ConsoleStrategy() {}
        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex); // 加锁,会随着析构自动释放
            std::cout << message << gsep;
        }

    private:
        Mutex _mutex;
    };

    // 文件打印日志的派生类
    const std::string defaultpath = "./log/";
    const std::string defaultfile = "my.log";
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath,
                        const std::string &file = defaultfile)
            : _path(path), _file(file)
        {
            LockGuard lockguard(_mutex);
            if (std::filesystem::exists(_path)) // 如果路径存在
            {
                return;
            }
            // 不存在则创建
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }

        void SyncLog(const std::string &message) override
        {
            LockGuard lockguard(_mutex);
            std::string filename = _path + _file;       //"./log/my.log"
            std::ofstream out(filename, std::ios::app); // 追加写入的方式打开
            if (!out.is_open())
            {
                return;
            }
            out << message << gsep;
            out.close();
        }

    private:
        std::string _path; // 日志文件所在路径
        std::string _file; // 日志文件本身
        Mutex _mutex;
    };

    // 形成一条完整的日志

    // 1.日志等级
    enum class LogLevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    std::string LevelToString(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }
    std::string GetTimeStamp()
    {
        time_t curr = time(nullptr);
        struct tm curr_tm;
        localtime_r(&curr,&curr_tm);
        char timebuffer[128];
        snprintf(timebuffer,sizeof(timebuffer),"%4d-%02d-%02d %02d:%02d:%02d",
            curr_tm.tm_year + 1900,
            curr_tm.tm_mon + 1,
            curr_tm.tm_mday,
            curr_tm.tm_hour,
            curr_tm.tm_min,
            curr_tm.tm_sec
        );
        return timebuffer;
    }   

    class Logger
    {
    public:
        Logger()
        {
            // 默认使用显示器打印策略
            _fflush_strategy = std::make_unique<ConsoleStrategy>();
        }
        void EnableFileLogStrategy() // 切换File刷新策略
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
        void EnableConsoleLogStrategy() // 切换Console刷新策略
        {
            _fflush_strategy = std::make_unique<ConsoleStrategy>();
        }
        // 内部类，表示未来的一条日志
        class LogMessage
        {
        public:
            LogMessage(LogLevel &level, std::string &src_name, int line, Logger &logger)
                : _curr_time(GetTimeStamp())
                , _level(level), _pid(getpid())
                , _src_name(src_name)
                , _line(line)
                , _logger(logger)
            {
                // 日志的属性部分合并在一起
                std::stringstream ss;
                ss << "[" << _curr_time << "]"
                   << "[" << LevelToString(_level) << "]"
                   << "[" << _pid << "]"
                   << "[" << _src_name << "]"
                   << "[" << _line << "]"
                   << "-";

                _loginfo = ss.str();
            }

            // 重载，支持这种形式：LogMessage()<<"hehe"<<"haha"<<...
            template <typename T>
            LogMessage &operator<<(const T &info)
            {
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }

            ~LogMessage() 
            {
                //刷新消息
                if(_logger._fflush_strategy)
                {
                    _logger._fflush_strategy->SyncLog(_loginfo);
                }
            }

        private:
            std::string _curr_time; // 日志时间
            LogLevel _level;        // 日志等级
            pid_t _pid;             // 进程ID
            std::string _src_name;  // 文件名
            int _line;              // 行号
            std::string _loginfo;   // 合并之后，一条完整的信息
            Logger &_logger;
        };
        //Logger(...) ---> LogMessage()>>"..."
        LogMessage operator()(LogLevel level,std::string src_name,int line)
        {
            return LogMessage(level,src_name,line,*this);
        }
        ~Logger() {}

    private:
        std::unique_ptr<LogStrategy> _fflush_strategy;
    };

    //全局日志对象
    Logger logger;
    //使用宏，简化用户操作，获取文化名和行号
    #define LOG(level) logger(level,__FILE__,__LINE__)
    #define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()
}